// packageB/member/distribution_queue/queue/queue.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    member_id:"",
    invite_code:'',
    showStartTime: false,
    showEndTime: false,
    language: "",
    level_name: "",
    nickname: "",
    avatar: "",
    total_activity: "",
    total_sales_amount: "",
    estimated_commission: "",
    unsettled_commission: "",
    settled_commission: "",
    undelivered_commission: "",
    delivered_commission: "",
    accumulated_income: '',
    order_count: "",
    activeName: "first",
    activity_list: [],
    status: 3, //3全部，0活动中，1已完成 ，-1失败
    //more
    isLoadMore: true,
    page: 1,
    count: 0,
    imgPath: app.globalData.imgPath,
    offset: 0,
    limit: 15,
    starttime_str: '',
    endtime_str: '',
    end_time: new Date().getTime(),
    begin_time: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`
      }
      return value;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //let currentTime = this.timestampToTime(new Date().getTime())
    let dateObj = new Date(); // 创建Date对象
    let year = dateObj.getFullYear(); // 获取年份
    let month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取月份，并补零
    let day = ("0" + dateObj.getDate()).slice(-2); // 获取日期，并补零
    let currentTime = `${year}-${month}-${day}`;
    this.setData({
      starttime_str:currentTime,
      endtime_str:currentTime,
      member_id:wx.getStorageSync("yz_uid"),
      invite_code:wx.getStorageSync("invite_code")
    })
    this.getData();
    this.getInfo();
    
  },
  onClearSearch() {
    let currentTime = this.timestampToTime(new Date().getTime())
    this.setData({
      list: [],
      count: 0,
      offset: 0,
      total_activity: "",
      total_sales_amount: "",
      estimated_commission: "",
      unsettled_commission: "",
      settled_commission: "",
      undelivered_commission: "",
      delivered_commission: "",
      accumulated_income: '',
      order_count: "",
      activity_list: [],
      starttime_str: currentTime,
      endtime_str: currentTime,
      end_time: new Date().getTime(),
      begin_time: new Date().getTime()
    })
    this.getData();
  },
  onSearch() {
    this.setData({
      list: [],
      count: 0,
      offset: 0,
      total_activity: "",
      total_sales_amount: "",
      estimated_commission: "",
      unsettled_commission: "",
      settled_commission: "",
      undelivered_commission: "",
      delivered_commission: "",
      accumulated_income: '',
      order_count: "",
      activity_list: []
    })
    this.getData();
  },
  handleClickStart() {
    this.setData({
      showStartTime: true
    })
  },
  handleClickEnd() {
    this.setData({
      showEndTime: true
    })
  },
  closeStartShow() {
    this.setData({
      showStartTime: false
    })
  },
  closeEndShow() {
    this.setData({
      showEndTime: false
    })
  },
  onStartConfirm(e) {
    if(isNaN(e.detail)){
      this.closeStartShow();
      return true
    }
    let time = this.timestampToTime(e.detail);
    this.setData({
      starttime_str: time
    })
    this.closeStartShow();
  },
  onEndConfirm(e) {
    if(isNaN(e.detail)){
      this.closeEndShow()
      return true;

    }
    let time = this.timestampToTime(e.detail);
    
    console.log(e)
    this.setData({
      endtime_str: time
    })
    this.closeEndShow()
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
    //日期转化
  timestampToTime(timestamp) {
    let dateObj = new Date(timestamp); // 创建Date对象
    let year = dateObj.getFullYear(); // 获取年份
    let month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取月份，并补零
    let day = ("0" + dateObj.getDate()).slice(-2); // 获取日期，并补零
    
    return `${year}-${month}-${day}`; // 返回转换后的日期格式
  },
  //日期转化
  // timestampToTime(timestamp) {
  //   var date = new Date(timestamp);
  //   let Y = date.getFullYear() + "-";
  //   let M =
  //     (date.getMonth() + 1 < 10 ?
  //       "0" + (date.getMonth() + 1) :
  //       date.getMonth() + 1) + "-";
  //   let D = this.change(date.getDate()) + " ";
  //   return Y + M + D;
  // },
  getInfo() {
    let that = this;
    let urlStr = app.getNetAddresss(`plugin.newcomer-fission.frontend.controllers.center.index`);
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            avatar: res.data.info.avatar,
            nickname: res.data.info.nickname,
            level_name: res.data.info.level_name
          })
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });

  },
  getData() {
    let that = this;
    let time = '';
    if (this.data.starttime_str != "" && this.data.endtime_str != "") {
      time = `&begin_time=${this.timestampToTime(this.data.starttime_str)}&end_time=${this.timestampToTime(this.data.endtime_str)}`
      time = time.replace(/\s*/g,'')
    }
    let urlStr = app.getNetAddresss(`member.teamDividendStatistics.get-list&limit=${this.data.limit}&offset=${this.data.offset}${time}`);
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let list = that.data.activity_list.concat(res.data.shared_list)
          that.setData({
            nickname: res.data.nickname,
            avatar: res.data.avatar,
            total_activity: res.data.total_activity,
            total_sales_amount: res.data.total_sales_amount,
            estimated_commission: res.data.estimated_commission,
            unsettled_commission: res.data.unsettled_commission,
            settled_commission: res.data.settled_commission,
            undelivered_commission: res.data.undelivered_commission,
            delivered_commission: res.data.delivered_commission,
            accumulated_income: res.data.accumulated_income,
            order_count: res.data.order_count,
            activity_list: list,
            count: res.data.shared_count,
          });
          if (res.data.name) {
            wx.setNavigationBarTitle({
              title: res.data.name + "查询",
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  _getMoreData() {
    const that = this;
    let json = {
      page: this.data.page,
      status: this.data.status,
    };
    let api = `member.teamDividendStatistics.get-list&limit=${this.data.limit}&offset=${this.data.offset}`;
    let urlStr = "";
    that.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.activity_list.length >= this.data.total_page) {
      return;
    } else {
      this.data.offset = this.data.offset + 1;
      urlStr = app.getNetAddresss(api);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              isLoadMore: true,
              activity_list: that.data.activity_list.concat(res.data.shared_list),
            });
          } else {
            that.setData({
              page: that.data.offset - 1,
              isLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  copybtn(e) {
    console.log(e)
    let inviteCode = e.target.dataset.num;
    wx.setClipboardData({
      data: inviteCode ? inviteCode : "",
      success(res) {
        wx.showToast({
          icon: "none",
          title: "复制成功",
          duration: 1000,
        });
      },
    });
  },
  handleClick(e) {
    let index = e.detail.index;
    if (index == 0) {
      this.data.status = "3";
    } else if (index == 1) {
      this.data.status = "0";
    } else if (index == 2) {
      this.data.status = "1";
    } else if (index == 3) {
      this.data.status = "-1";
    }
    this.getListData();
  },
  getListData() {
    let that = this;
    this.isLoadMore = false;
    this.page = 1;
    this.total_page = 0;
    this.setData({
      activity_list: [],
    });
    let urlStr = app.getNetAddresss("plugin.commission-activity.api.activity-inquire.index");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        page: this.data.page,
        status: this.data.status,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let activity = res.data.activity;
          that.setData({
            activity_list: activity.data,
            page: activity.current_page,
            total_page: activity.last_page,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.activity_list.length >= this.data.count) {
      return true;
    }
    this.setData({
      offset: this.data.offset + 1
    })
    this.getData();
    // if (this.data.isLoadMore) {
    //   this._getMoreData();
    // } else {
    //   console.log("没有更多数据");
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  gotoDetail(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/packageB/member/distribution_queue/DistributionActivityDetail/DistributionActivityDetail?id=${id}&begin_time=${this.data.starttime_str}&end_time=${this.data.endtime_str}`,
    });
  },
  gotoCommision(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageB/member/distribution_queue/DistributionCommissionDetail/DistributionCommissionDetail?id=" + id,
    });
  },
  gotoOrder(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageA/member/orderdetail/orderdetail?order_id=" + id + "&orderType=" + "commission_activity",
    });
  },
  gotoParticipant(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageB/member/distribution_queue/DistributionParticipant/DistributionParticipant?id=" + id,
    });
  },
  
});